//
//  XLWebPlugin4.m
//  campus
//
//  Created by xl on 2019/12/31.
//  Copyright © 2019 xl. All rights reserved.
//

#import "XLWebPlugin4.h"
#import "XLAppletManager.h"
#import "AppStartUpConfig.h"
#import "XLCameraRecordTool.h"
#import "XLUploadFileTool.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "XLUserDefaults.h"

#define XLJumpToLogin   @"toLogin"
#define XLDeletePicureAndVideo   @"toDeletePictureAndVideo"
#define XLgetUserInfo   @"toGetUserInfo"
#define XLOpenSystemAlbum  @"toOpenSystemAlbum"
#define XLOpenSystemCamera @"toOpenSystemCamera"
#define XLGetOssSecurityToken @"toGetOssSecurityToken"


@interface XLWebPlugin4 ()

@property (nonatomic, strong) AUToast *toastLoad;

@end
@implementation XLWebPlugin4

#pragma mark - 重写父类方法
- (void)pluginDidLoad {
    self.scope = kPSDScope_Scene;
    [self.target addEventListener:kNBEvent_Scene_LoadRequest_All withListener:self useCapture:NO];
    [super pluginDidLoad];
    
}

- (void)addJSApis {
    [super addJSApis];
    //退出登录
    PSDJsApi *loginJsApi = [PSDJsApi jsApi:XLJumpToLogin handler:^(NSDictionary *data, PSDContext *context, PSDJsApiResponseCallbackBlock responseCallbackBlock) {
        NSLog(@"AAAAA%@  %@",data, context);
        UIViewController *vc = context.currentViewController;
        NSDictionary *params = context.currentScene.createParam.expandParams;
        if ([params objectForKey:@"appId"]) {
            [XLAppletManager exitAllMpassAppletWithAppId:params[@"appId"]];//退出当前小程序
        }
        [[AppStartUpConfig sharedAppStartUpConfig] jumpLoginRegsiterControllerWithVC:(XLBaseViewController *)vc];
        responseCallbackBlock(@{});
    } checkParams:NO isPrivate:NO scope:self.scope];
    [self registerJsApi2Target:loginJsApi];
    
    //获取securityToken
    PSDJsApi *ossTokenJsApi = [PSDJsApi jsApi:XLGetOssSecurityToken handler:^(NSDictionary *data, PSDContext *context, PSDJsApiResponseCallbackBlock responseCallbackBlock) {
        [self requestOSSSecurityTokenToUploadDatas:nil operationType:1 viewControl:nil responseCallbackBlock:responseCallbackBlock];
    } checkParams:NO isPrivate:NO scope:self.scope];
    [self registerJsApi2Target:ossTokenJsApi];
    
    //打开系统摄像头,上传视频
    PSDJsApi *cameraJsApi = [PSDJsApi jsApi:XLOpenSystemCamera handler:^(NSDictionary *data, PSDContext *context, PSDJsApiResponseCallbackBlock responseCallbackBlock) {
        UIViewController *vc = context.currentViewController;
        [[XLCameraRecordTool sharedXLCameraRecordTool] startCameraRecordViewController:vc completeBlock:^(id data) {
            if (data) {
//                [self requestOSSSecurityTokenToUploadDatas:@[data] operationType:3 responseCallbackBlock:responseCallbackBlock];
                [self requestOSSSecurityTokenToUploadDatas:@[data] operationType:3 viewControl:vc responseCallbackBlock:^(id responseData) {
                    [vc callHandler:@"systemCameraCallback" data:responseData responseCallback:^(id response) {
                        NSLog(@"打开系统摄像头,上传视频回调%@",response);
                    }];
                }];
            } else {
                responseCallbackBlock(@{@"result_code":@(NO)});
            }
        }];
        
    } checkParams:NO isPrivate:NO scope:self.scope];
    [self registerJsApi2Target:cameraJsApi];
    
    //打开相册
    PSDJsApi *albumJsApi = [PSDJsApi jsApi:XLOpenSystemAlbum handler:^(NSDictionary *data, PSDContext *context, PSDJsApiResponseCallbackBlock responseCallbackBlock) {
        UIViewController *vc = context.currentViewController;
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:nil];
        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePickerVc.allowPickingVideo = YES;
        imagePickerVc.allowPickingGif = NO;
        imagePickerVc.allowPickingImage = YES;
        imagePickerVc.sortAscendingByModificationDate = NO;
        // 你可以通过block或者代理，来得到用户选择的照片.
        
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            //选择了照片
            NSMutableArray *temArr = [NSMutableArray array];
            for (UIImage *image in photos) {
                NSData *data = UIImageJPEGRepresentation(image, 1);
                [temArr addObject:data];
            }
            if (temArr.count > 0) {
//                [self requestOSSSecurityTokenToUploadDatas:temArr operationType:2 responseCallbackBlock:responseCallbackBlock];
                [self requestOSSSecurityTokenToUploadDatas:temArr operationType:2 viewControl:vc responseCallbackBlock:^(id responseData) {
                    [vc callHandler:@"systemCameraCallback" data:responseData responseCallback:^(id response) {
                        NSLog(@"本地相册上传回调%@",response);
                    }];
                }];
            } else {
                responseCallbackBlock(@{@"result_code":@(NO)});
            }
        }];
        
        [imagePickerVc setImagePickerControllerDidCancelHandle:^{
             responseCallbackBlock(@{@"result_code":@(NO)});
        }];
        
        [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset) {
            //选择了视频
            if (asset == nil) {
                responseCallbackBlock(@{@"result_code":@(NO)});
                return;
            }
            [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
                // NSData *data = [NSData dataWithContentsOfFile:outputPath];
//                [self requestOSSSecurityTokenToUploadDatas:@[[NSURL fileURLWithPath:outputPath]] operationType:3 responseCallbackBlock:responseCallbackBlock];
                [self requestOSSSecurityTokenToUploadDatas:@[[NSURL fileURLWithPath:outputPath]] operationType:3 viewControl:vc responseCallbackBlock:^(id responseData) {
                    [vc callHandler:@"systemCameraCallback" data:responseData responseCallback:^(id response) {
                        NSLog(@"本地相册上传视频回调%@",response);
                    }];
                }];

                NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
                // Export completed, send video here, send by outputPath or NSData
                // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
            } failure:^(NSString *errorMessage, NSError *error) {
                NSLog(@"视频导出失败");
                responseCallbackBlock(@{@"result_code":@(NO)});
            }];
        }];
        [vc presentViewController:imagePickerVc animated:YES completion:nil];
    } checkParams:NO isPrivate:NO scope:self.scope];
    [self registerJsApi2Target:albumJsApi];
    
    PSDJsApi *deleteOssJsApi = [PSDJsApi jsApi:XLDeletePicureAndVideo handler:^(NSDictionary *data, PSDContext *context, PSDJsApiResponseCallbackBlock responseCallbackBlock) {
        NSString *filePath = [data objectForKey:@"filePath"];
        if (ISEmptyString(filePath)) {
            responseCallbackBlock(@{@"result_code":@(NO)});
        } else {
            [self requestOSSSecurityTokenToUploadDatas:@[filePath] operationType:4 viewControl:nil responseCallbackBlock:responseCallbackBlock];
        }
        responseCallbackBlock(@{@"result_code":@(NO)});
    } checkParams:NO isPrivate:NO scope:self.scope];
    [self registerJsApi2Target:deleteOssJsApi];
    
    // 获取用户信息
    PSDJsApi *getUserInfoJsApi = [PSDJsApi jsApi:XLgetUserInfo handler:^(NSDictionary *data, PSDContext *context, PSDJsApiResponseCallbackBlock responseCallbackBlock) {
        [self getUserInforResponseCallbackBlock:responseCallbackBlock];
    } checkParams:NO isPrivate:NO scope:self.scope];
    [self registerJsApi2Target:getUserInfoJsApi];

}

/// 监听的事件触发后的逻辑
/// @param event 事件
- (void)handleEvent:(PSDEvent *)event {
    [super handleEvent:event];
    XLLog(@"监听的事件%@",event);
    
}
/// 避免自定义插件被覆盖，需要设置插件的高优先级。
- (int)priority
{
    return PSDPluginPriority_High +1;
}


#pragma mark - net
/**
 *用于获取securityToken
 *
 * @param datas 用于数据数组
 *
 * @param operationType 1表示直接获取securityToken   2表示上传图片获取securityToken 3表示上传视频获取securityToken   4表示删除图片或视频获取，获取securityToken
 *
 */
- (void)requestOSSSecurityTokenToUploadDatas:(NSArray *)datas
                               operationType:(NSInteger)operationType
                               viewControl:(UIViewController *)vc
                       responseCallbackBlock:(PSDJsApiResponseCallbackBlock)responseCallbackBlock {
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (!ISEmptyString(XL_UserInfoData.securityToken)) {
        [params setValue:XL_UserInfoData.securityToken forKey:@"securityToken"];
    }
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLFetchOSSTokenUrl params:params isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        id temData = [dict objectForKey:@"data"];
        if ([temData isKindOfClass:[NSDictionary class]]) {
            [[XLUploadFileTool sharedInstance] initClientWithServerDic:temData];
            if (operationType == 1) {//直接获取securityToken
                NSMutableDictionary *temDic = [[NSMutableDictionary alloc] initWithDictionary:temData];
                [temDic setValue:@(YES) forKey:@"result_code"];
                responseCallbackBlock(temDic);
            } else if (operationType ==2) { //上传图片
                [strongSelf uploadPicturesToServer:datas responseCallbackBlock:responseCallbackBlock];
            } else if (operationType == 3) {//上传视频
                [strongSelf uploadVideoToServerPathUrl:datas.firstObject viewControl:vc responseCallbackBlock:responseCallbackBlock];
            } else {//删除图片或者视频，获取securitytoken
                [strongSelf deleteOssFilesPathNames:datas responseCallbackBlock:responseCallbackBlock];
            }
        } else {
            responseCallbackBlock(@{@"result_code":@(NO)});
        }

    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
         responseCallbackBlock(@{@"result_code":@(NO)});
    }];
}

//上传图片
- (void)uploadPicturesToServer:(NSArray *)dataArr
      responseCallbackBlock:(PSDJsApiResponseCallbackBlock)responseCallbackBlock {
    [[XLUploadFileTool sharedInstance] uploadImagesData:dataArr successBlock:^(NSDictionary *dict) {
        responseCallbackBlock(dict);
        XLLog(@"给小程序回传内容:>>>>>%@", dict);
    } failBlock:^(NSError *error, XLNetworkReachabilityStatus reachabilityStatus) {
        XLLog(@"给小程序回传内容失败:>>>>>");
        responseCallbackBlock(@{@"result_code":@(NO)});
    }];
}


/// 上传视频 ,获取视频资源，和获取视频首帧资源，同步上传图片操作，同步上传视频操作，把资源合并发送。
/// @param pathUrl 视频路径
/// @param responseCallbackBlock 回调
- (void)uploadVideoToServerPathUrl:(NSURL *)pathUrl viewControl:(UIViewController *)vc responseCallbackBlock:(PSDJsApiResponseCallbackBlock)responseCallbackBlock {
    
    dispatch_queue_t queue = dispatch_queue_create("shipinshangchuan", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        UIImage * image = [self getVideoPreViewImage:pathUrl];
        if (!image) {
            responseCallbackBlock(@{@"result_code":@(NO)});
        }
        NSData * data = UIImageJPEGRepresentation(image, 1);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        
        __block int a = 0;
        
        __block NSDictionary * dictz;
        __block NSString * poster;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showLoadingAnimalWithTitle:@"视频上传中" onView:vc.view];
        });
        
        
      
        [[XLUploadFileTool sharedInstance] uploadVideoDataPathUrl:pathUrl successBlock:^(NSDictionary *dict) {
            XLLog(@"给小程序回传内容:>>>>>%@", dict);
            dictz = dict;
            a = a + 1;
    //        responseCallbackBlock(dict);
        } failBlock:^(NSError *error, XLNetworkReachabilityStatus reachabilityStatus) {
            XLLog(@"给小程序回传内容失败:>>>>>");
            [self hideLoadingAnimal];
            responseCallbackBlock(@{@"result_code":@(NO)});
            a = a + 4;
        }];
       
        [[XLUploadFileTool sharedInstance] uploadThumbnailData:data successBlock:^(NSDictionary *dict) {
    //        responseCallbackBlock(dict);
            XLLog(@"给小程序回传内容:>>>>>%@", dict);
            poster = dict[@"content"];
            a = a + 2;
        } failBlock:^(NSError *error, XLNetworkReachabilityStatus reachabilityStatus) {
            XLLog(@"给小程序回传内容失败:>>>>>");
            a = a + 8;
            [self hideLoadingAnimal];
            responseCallbackBlock(@{@"result_code":@(NO)});
        }];
        
        
        while (a >= 3) {
            
            dispatch_semaphore_signal(semaphore);
            break;
        }

        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"dispatch_group_wait 结束");
        if (a > 3) return;
        
        NSMutableDictionary * dicte = [NSMutableDictionary dictionaryWithDictionary:dictz];
        [dicte setObject:poster forKey:@"coverPicture"];
        [self hideLoadingAnimal];
        responseCallbackBlock(dicte);
        NSLog(@"视频，和缩略图%@",dicte);
    });
    

    
}

// 获取视频第一帧
 
- (UIImage*) getVideoPreViewImage:(NSURL *)path{
    //本地视频
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    //网络视频
//    AVURLAsset *asset2 = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:path] options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    if (videoImage == nil) {
        videoImage = [UIImage imageNamed:@"default_video.png"];
    }
    return videoImage;
}


//删除文件
- (void)deleteOssFilesPathNames:(NSArray *)pathNames
          responseCallbackBlock:(PSDJsApiResponseCallbackBlock)responseCallbackBlock {
    [[XLUploadFileTool sharedInstance] deleteOssExitFiles:pathNames successBlock:^(NSDictionary *dict) {
        XLLog(@"AAAA%@", dict);
        responseCallbackBlock(dict);
    } failBlock:^(NSError *error) {
        responseCallbackBlock(@{@"result_code":@(NO)});
    }];
}

//获取个人信息
- (void)getUserInforResponseCallbackBlock:(PSDJsApiResponseCallbackBlock)responseCallbackBlock {
    

    NSData *userData = [XLUserDefaults getCurrentLoginUserInfoJson];
    NSDictionary *dict = @{};
    if (userData != nil) {
        dict = [NSJSONSerialization JSONObjectWithData:userData options:0 error:nil];
    }
    if (dict.count<0) {
        responseCallbackBlock(@{@"result_code":@(NO)});
    }else{
        responseCallbackBlock(dict);
    }
}

//加载动画
- (void)showLoadingAnimalWithTitle:(NSString *)title onView:(UIView *)view{
//    self.toastLoad = [AUToast presentModalToastWithin:view withIcon:AUToastIconLoading text:title duration:60 logTag:@"loading" completion:nil];
}

//隐藏动画
- (void)hideLoadingAnimal {
//    if (self.toastLoad) {
//        [self.toastLoad dismissToast];
//    }
}
@end
